package com.kuaiditu.assistant.ui.scan;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.assistant_api.AssistantApi;
import com.kuaiditu.assistant.api.assistant_api.base.AssistantResponse;
import com.kuaiditu.assistant.base.BaseActivity;
import com.kuaiditu.assistant.entity.TaskExpressItem;
import com.kuaiditu.assistant.event.RefreshEvent;
import com.kuaiditu.assistant.module.retrofit.ProgressSubscriber;
import com.kuaiditu.assistant.ui.dialog.TaskInfoDialog;
import com.kuaiditu.assistant.util.LogUtil;
import com.kuaiditu.assistant.view.topbar.TopBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.iwgang.simplifyspan.SimplifySpanBuild;
import cn.iwgang.simplifyspan.unit.SpecialTextUnit;


@Route(path = SignScanActivity.PATH)
public class SignScanActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {


    public static final String PATH = "/user/sign_order";

    @BindView(R.id.top_bar)
    TopBar topBar;
    @BindView(R.id.rv_sign)
    RecyclerView rvSign;
    @BindView(R.id.swiper)
    SwipeRefreshLayout swiper;
    @BindView(R.id.btn_complete_add)
    Button btnCompleteAdd;

    @Autowired
    int task_id;

    @Autowired
    int express_com_id;


    private DeliveryAdapter mDeliveryAdapter;
    private List<TaskExpressItem> deliveries = new ArrayList<>();
    private AssistantApi mAssistantApi;

    @Override
    public int initContentView() {
        return R.layout.activity_sign_scan;
    }

    @Override
    public void initInjector() {
        ARouter.getInstance().inject(this);
        mAssistantApi = getApplicationComponent().getApiManager().getAssistantApi();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        topBar.bind(this, true);

        swiper.setOnRefreshListener(this);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);

        rvSign.setLayoutManager(linearLayoutManager);
        rvSign.addItemDecoration(new DividerItemDecoration(rvSign.getContext(), linearLayoutManager.getOrientation()));

        rvSign.setAdapter(mDeliveryAdapter = new DeliveryAdapter(deliveries,express_com_id));

        onRefresh();

    }


    @OnClick(R.id.btn_complete_add)
    public void onViewClicked() {

        ARouter.getInstance().build(ScanExpressSheetActivity.PATH)
                .withInt("task_id", task_id)
                .withInt("scan_type", 1)
                .withInt("express_com_id", express_com_id)
                .navigation(this, 1001);

    }

    @Override
    public void onRefresh() {
        swiper.setRefreshing(true);
        fetchOrderList();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("完成");
        menuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
//        menuItem.setIcon(R.mipmap.ic_scan);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            return super.onOptionsItemSelected(item);
        } else {

            SimplifySpanBuild spanBuild = new SimplifySpanBuild();
            int waitCount = 0;
            int signCount = 0;
            int errorCount = 0;

            for (TaskExpressItem taskExpressItem : mDeliveryAdapter.getData()) {
                if (taskExpressItem.getOrderItem_status().equals("SEND")) {
                    signCount++;
                } else if (taskExpressItem.getOrderItem_status().equals("ADD")) {
                    waitCount++;
                } else {
                    errorCount++;
                }
            }

            spanBuild.append(new SpecialTextUnit("请确认数量\n", Color.parseColor("#333333")))
                    .append(new SpecialTextUnit(String.format("列表中共%s个已签收\n", signCount), Color.parseColor("#666666")))
                    .append(new SpecialTextUnit(String.format("%s个待签收单\n", waitCount), Color.RED))
                    .append(new SpecialTextUnit(String.format("%s个异常单", errorCount), Color.RED));

            TaskInfoDialog taskInfoDialog = (TaskInfoDialog) ARouter.getInstance().build(TaskInfoDialog.PATH).navigation();
            taskInfoDialog.setMessage(spanBuild.build());
            taskInfoDialog.setTextGravity(Gravity.CENTER);
            taskInfoDialog.setOnTakeTaskClickListener("确定", new TaskInfoDialog.onTakeTaskClickListener() {
                @Override
                public void onClick() {
                    completeSignOrder();
                }
            });
            taskInfoDialog.show(getSupportFragmentManager(), TaskInfoDialog.PATH);





            return true;
        }
    }


    private void fetchOrderList() {
        mAssistantApi.fetchTaskOrderList(task_id)
                .subscribe(new ProgressSubscriber<List<TaskExpressItem>>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(List<TaskExpressItem> taskExpressItems) {
                        deliveries.clear();
                        deliveries.addAll(taskExpressItems);
                        mDeliveryAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
                        swiper.setRefreshing(false);
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            onRefresh();
        }
    }


    private void completeSignOrder() {
        mAssistantApi.completeSignOrder(String.valueOf(task_id))
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onNext(AssistantResponse assistantResponse) {
                        setResult(Activity.RESULT_OK);
                        EventBus.getDefault().post(new RefreshEvent());
                        finish();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new RefreshEvent());
        super.onDestroy();
        LogUtil.e("send event RefreshEvent");
    }
}
